package com.yy.utils;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.yy.pojo.TestUser;
import com.yy.service.TestUserService;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author young
 * @date 2022/8/29 21:15
 * @description: 导入Excel文件需要的监听器工具类
 */
@Component
public class DataListener extends AnalysisEventListener<TestUser> {
    private TestUserService testUserService;

    public DataListener(TestUserService testUserService) {
        this.testUserService = testUserService;
    }

    List<TestUser> list = new ArrayList<>();

    /**
     * 读取数据时执行该方法，设置每5条信息进行存储一次然后清理list
     *
     * @param user
     * @param analysisContext
     */
    @Override
    public void invoke(TestUser user, AnalysisContext analysisContext) {
        list.add(user);
        if (list.size() == 5) {
            testUserService.saveBatch(list);
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        testUserService.saveBatch(list);
    }
}
